package com.googlecode.imule.plugin;

import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;

import org.eclipse.core.filebuffers.FileBuffers;
import org.eclipse.core.filebuffers.ITextFileBuffer;
import org.eclipse.core.filebuffers.ITextFileBufferManager;
import org.eclipse.core.filebuffers.LocationKind;
import org.eclipse.core.filebuffers.manipulation.TextFileBufferOperation;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.IDocument;
import org.eclipse.swt.widgets.Shell;

public class ASTManifest extends ASTAbstractManifest{

	@Override
	public void run(ICompilationUnit lwUnit) {
		CompilationUnit unit = parse(lwUnit);
		ComponentInfoDetector localVariableDetector = new ComponentInfoDetector();

		localVariableDetector.process(unit);
		write(lwUnit, localVariableDetector.name);
	}

	public void write(ICompilationUnit lwUnit, String name){
		IFolder container = (IFolder)lwUnit.getResource().getParent();	// not checked!!!!!!

		IPath path = lwUnit.getPath();

		String _name = lwUnit.getElementName().substring(0, lwUnit.getElementName().length()-5) + ".xml";
		// convert to an XML path
		//path = path.removeFileExtension().addFileExtension("xml");

		try {
			if (container != null){
				IFolder manifests = container.getFolder("manifests");
				if (!manifests.exists()){
					manifests.create(false, true, null);
				}
				// create the resource file
				IFile file = manifests.getFile(_name);
				
				// slightly awkward conversion to a inputStream
				InputStream bais = new ByteArrayInputStream("<?xml version=\"1.0\" encoding=\"UTF-8\"?><test>blah</test>".getBytes());
				
				file.create(bais, false, null);
				
				//file.appendContents(bais, false, false, null);
				

			} 
		} catch (CoreException e){
			// TODO: handle exception
		}
	}
}
